<template>
	<div style="background-color: #ffff7f;">
		<van-nav-bar title="上新车辆" left-text="返回" left-arrow @click-left="onClickLeft" />
		<div>
			<van-form @submit="onSubmitImg" v-show="show">
				<p>请至少上传一张封面图片</p>
				<van-uploader v-model="fileList" :max-count="1" />
				<van-button round block type="info" native-type="submit">提交</van-button>
			</van-form>
			<van-form @submit="onSubmitImgs" style="margin-top: 50px;">
				<p>上传更多图片</p>
				<van-uploader v-model="fileLists" />
				<van-button round block type="info" native-type="submit">提交</van-button>
			</van-form>
		</div>
	</div>
</template>

<script>
	import {
		Notify,
		Dialog
	} from 'vant';

	export default {
		data() {
			return {
				user: {},
				fileList: [],
				fileLists: [],
				carId: null,
				show: true
			}
		},
		methods: {
			onClickLeft() {
				this.$router.back();
			},
			/* 上传封面图片 */
			onSubmitImg() {
				let carImg = new FormData();
				let file = this.fileList[0].file;
				carImg.append("carId", this.carId);
				carImg.append("file", file)
				/* 网络请求 */
				this.$axios({
					method: 'post',
					url: '/carshop/upLoadFile',
					headers: {
						'UserId': this.user.userId,
						'CarToken': this.user.token,
						"Content-Type": "multipart/form-data"
					},
					data: carImg
				}).then((resp) => {
					if (resp.data.msg == "文件上传成功") {
						this.show = false;
						Dialog.alert({
							message: '添加成功',
						})
					} else {
						Dialog.alert({
							message: '添加失败',
						})
					}
				})

			},
			/* 上传更多的图片 */
			onSubmitImgs() {
				let carImg = new FormData();
				this.fileLists.forEach(function(e) {
					carImg.append("files", e.file)
				})
				carImg.append("carId", this.carId);

				this.$axios({
					method: 'post',
					url: '/carshop/upLoadFiles',
					headers: {
						'UserId': this.user.userId,
						'CarToken': this.user.token,
						"Content-Type": "multipart/form-data"
					},
					data: carImg
				}).then((resp) => {
					if (resp.data.msg == "文件上传完成") {
						Dialog.alert({
							message: '添加成功',
						})
						this.$router.replace("/shophome");
					} else {
						Dialog.alert({
							message: '添加失败',
						})
					}
				})

			}
		},
		mounted() {
			this.carId = this.$route.query.carId;
			console.log("新添加车的id为：" + this.carId);

			let user = this.$cookies.get('user');
			if (user != null) {
				this.user = user;
			} else {
				Notify({
					type: 'danger',
					message: '未登录或登录已失效，请重新登录'
				})
				this.$router.back()
			}
		}
	}
</script>

<style scoped>
</style>
